import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useCartStore = defineStore(
  'cart',
  () => {
    const cart = ref([])
    const addToCart = (goods) => {
      // 查找购物车中是否已有该商品
      const item = cart.value.find((item) => goods.id === item.id)
      if (item) {
        // 如果已有，数量累加
        item.count += goods.count
      } else {
        // 如果没有，添加到购物车
        cart.value.push(goods)
      }
    }

    const removeCart = (id) => {
      cart.value.forEach((item, index) => {
        if (item.id == id) {
          cart.value.splice(index, 1)
        }
      })
    }

    const cartCount = () => {
      let sum = 0
      cart.value.forEach((item) => {
        sum += item.count // 修改这里，使用 count 而不是 num
      })
      return sum || undefined
    }
    const totalPrice = () => {
      let sum = 0
      cart.value.forEach((item) => {
        if (item.selected) {
          sum += item.price * item.count
        }
      })
      return sum
    }
    const goodPrice = (num, price ) => {
      return (num * price).toFixed(2)
    }

    return { cart, addToCart, removeCart, cartCount, totalPrice, goodPrice }
  },
  {
    persist: {
      enabled: true,
      strategies: [
        {
          key: 'cart',
          storage: localStorage,
        },
      ],
    },
  },
)

export default useCartStore
